package com.coszero.utils.app

import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Build
import android.preference.PreferenceManager
import android.text.TextUtils
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.Properties
import java.util.Stack

/**
 * 应用程序配置类：用于保存用户相关信息及设置
 *
 * @author ydh
 */
class AppConfig {
    private var mContext: Context? = null

    //  public void setAccessInfo(String accessToken, String accessSecret,
    //                            long expiresIn) {
    //     if (accessInfo == null)
    //     accessInfo = new AccessInfo();
    //     accessInfo.setAccessToken(accessToken);
    //     accessInfo.setAccessSecret(accessSecret);
    //     accessInfo.setExpiresIn(expiresIn);
    //     // 保存到配置
    //     this.setAccessToken(accessToken);
    //     this.setAccessSecret(accessSecret);
    //     this.setExpiresIn(expiresIn);
    //  }
    //  public AccessInfo getAccessInfo() {
    // if (accessInfo == null && !StringUtils.isEmpty(getAccessToken()) &&
    // !StringUtils.isEmpty(getAccessSecret())) {
    // accessInfo = new AccessInfo();
    // accessInfo.setAccessToken(getAccessToken());
    // accessInfo.setAccessSecret(getAccessSecret());
    // accessInfo.setExpiresIn(getExpiresIn());
    // }
    //    return accessInfo;
    //  }
    fun get(key: String?): String? {
        val props = get()
        return if ((props != null)) props.getProperty(key) else null
    }

    fun get(): Properties {
        var fis: FileInputStream? = null
        val props = Properties()
        try {
            // 读取files目录下的config
            // fis = activity.openFileInput(APP_CONFIG);

            // 读取app_config目录下的config

            val dirConf = mContext!!.getDir(APP_CONFIG, Context.MODE_PRIVATE)
            fis = FileInputStream(
                (dirConf.path + File.separator
                        + APP_CONFIG)
            )

            props.load(fis)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                fis?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return props
    }

    private fun setProps(p: Properties) {
        var fos: FileOutputStream? = null
        try {
            // 把config建在files目录下
            // fos = activity.openFileOutput(APP_CONFIG, Context.MODE_PRIVATE);

            // 把config建在(自定义)app_config的目录下

            val dirConf = mContext!!.getDir(APP_CONFIG, Context.MODE_PRIVATE)
            val conf = File(dirConf, APP_CONFIG)
            fos = FileOutputStream(conf)

            p.store(fos, null)
            fos.flush()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                fos?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun set(ps: Properties) {
        val props = get()
        props.putAll(ps)
        setProps(props)
    }

    fun set(key: String?, value: String?) {
        val props = get()
        props.setProperty(key, value)
        setProps(props)
    }

    fun remove(vararg key: String) {
        val props = get()
        for (k in key) props.remove(k)
        setProps(props)
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        var activity = activity
        if (activity != null) {
            activityStack!!.remove(activity)
            activity.finish()
            activity = null
        }
    }

    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity?) {
        if (activityStack == null) {
            activityStack = Stack()
        }
        activityStack!!.add(activity)
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        var i = 0
        val size = activityStack!!.size
        while (i < size) {
            if (null != activityStack!![i]) {
                activityStack!![i]!!.finish()
            }
            i++
        }
        activityStack!!.clear()
    }

    companion object {
        private const val APP_CONFIG = "config"
        private var activityStack: Stack<Activity?>? = null

        // 单例模式
        private var appConfig: AppConfig? = null

        const val CONF_APP_UNIQUEID: String = "APP_UNIQUEID"

        // URL身份认证
        const val CONF_AUTHPARAMS_SDKVERSION: String = "sdkVersion"
        const val CONF_AUTHPARAMS_APPID: String = "appId"
        const val CONF_AUTHPARAMS_CURRENT_TIME_ST: String = "ts"
        const val CONF_AUTHPARAMS_APPTOKEN: String = "token"

        //  private AccessInfo accessInfo = null;
        private var APPID: String? = null
        private var APPKEY: String? = null
        private const val SDK_VERSION = "1.0"

        fun getAppConfig(context: Context?): AppConfig {
            if (appConfig == null) {
                appConfig = AppConfig()
                appConfig!!.mContext = context
                //			initAppIdAndAppKey(context);
            }
            return appConfig!!
        }

        val sdkAuthParams: HashMap<String, String?>
            /**
             * 获取SDK验证有效性的Params
             *
             * @return
             */
            get() {
                val result =
                    HashMap<String, String?>()

                result[CONF_AUTHPARAMS_APPID] = APPID
                result[CONF_AUTHPARAMS_SDKVERSION] = SDK_VERSION
                result[CONF_AUTHPARAMS_CURRENT_TIME_ST] =
                    System.currentTimeMillis().toString()

                //    result.put(AppConfig.CONF_AUTHPARAMS_APPTOKEN,
//            Verify.getToken(result, AppConfig.APPKEY));
                return result
            }

        /**
         * 初始化APPID 获取App的包名<br></br>
         * 初始化APP_KEY 获取在manifest.xml中注册的数据
         *
         * @param context
         */
        private fun initAppIdAndAppKey(context: Context) {
            if (TextUtils.isEmpty(APPID)) {
                APPID = context.packageName
                var appKey = ""
                try {
                    val applicationInfo = context.packageManager
                        .getApplicationInfo(
                            context.packageName,
                            PackageManager.GET_META_DATA
                        )
                    appKey = applicationInfo.metaData.getString("Airport_SDK_Key").toString()
                } catch (e: PackageManager.NameNotFoundException) {
                    e.printStackTrace()
                }
                APPKEY = appKey
            }
        }

        /**
         * 获取Preference设置
         */
        fun getSharedPreferences(context: Context?): SharedPreferences {
            return PreferenceManager.getDefaultSharedPreferences(context)
        }

        /**
         * 判断当前版本是否兼容目标版本的方法
         *
         * @param VersionCode
         * @return
         */
        fun isMethodsCompat(VersionCode: Int): Boolean {
            val currentVersion = Build.VERSION.SDK_INT
            return currentVersion >= VersionCode
        }
    }
}
